<template>
  <div class="form-panel">
    <n-card class="card-wrap">
      <n-grid cols="2 s:2 m:4 l:4 xl:4 2xl:4" :x-gap="12" :y-gap="8" responsive="screen">
        <n-gi>
          <div class="column">
            <span class="column-title">产品ID</span>
            <n-select
              v-model:value="productValue"
              :options="product.options"
              placeholder="请选择产品ID"
              :status="product.status.value"
              @blur="() => (product.status.value = '')"
            />
          </div>
        </n-gi>
        <n-gi>
          <div class="column">
            <span class="column-title">供应链公司代码</span>
            <n-select
              v-model:value="supplierValue"
              :options="supplier.options"
              placeholder="请选择供应链公司代码"
              :status="supplier.status.value"
              @blur="() => (supplier.status.value = '')"
            />
          </div>
        </n-gi>
        <n-gi>
          <div class="column">
            <span class="column-title">代工厂代码</span>
            <n-select
              v-model:value="foundryValue"
              :options="foundry.options"
              placeholder="请选择代工厂代码"
              :status="foundry.status.value"
              @blur="() => (foundry.status.value = '')"
            />
          </div>
        </n-gi>
        <n-gi>
          <div class="column">
            <span class="column-title">生成SN码数量</span>
            <n-input-number
              v-model:value="codeNumber"
              :min="0"
              placeholder="请输入生成SN码数量"
              :status="codeNumberStatus"
              @blur="() => (codeNumberStatus = '')"
              clearable
            />
          </div>
        </n-gi>
      </n-grid>
      <div class="operate">
        <n-button-group>
          <n-button type="primary" ghost @click="onCreateSNCode"> 生成SN码 </n-button>
          <n-button type="primary" ghost @click="onClearSNCode"> 清空SN码 </n-button>
          <n-button type="primary" ghost @click="onExportForm">
            <template #icon>
              <n-icon><IosCloudDownload /></n-icon>
            </template>
            导出Excel
          </n-button>
        </n-button-group>
      </div>
      <div>
        <n-spin :show="show">
          <DataTable :list="SNCodeList"></DataTable>
          <template #description> 生成中... </template>
        </n-spin>
      </div>
    </n-card>
  </div>
</template>

<script>
import { IosCloudDownload } from "@vicons/ionicons4";
import { defineComponent, ref } from "vue";
import { NCard, NSelect, NGrid, NGi, NButtonGroup, NButton, NInputNumber, useMessage, NIcon, NSpin } from "naive-ui";
import DataTable from "./DataTable.vue";
import exportExcel from "../utils/ExportToExcel";

let existCodeNumber = 0; // 已存在Code数量

export default defineComponent({
  components: {
    DataTable,
    NCard,
    NSelect,
    NGrid,
    NGi,
    NButtonGroup,
    NButton,
    NInputNumber,
    NIcon,
    IosCloudDownload,
    NSpin,
  },
  setup() {
    const message = useMessage();
    let product = {
      status: ref(null),
      options: [
        {
          label: "国内：39701",
          value: "39701",
        },
        {
          label: "欧规：39953",
          value: "39953",
        },
        {
          label: "韩规：39954",
          value: "39954",
        },
        {
          label: "日规：39955",
          value: "39955",
        },
      ],
    };

    let supplier = {
      status: ref(null),
      options: [
        {
          label: "BL",
          value: "BL",
        },
      ],
    };

    let foundry = {
      status: ref(null),
      options: [
        {
          label: "ADM",
          value: "ADM",
        },
      ],
    };

    return {
      message,
      productValue: ref(null),
      product,
      supplierValue: ref("BL"),
      supplier,
      foundryValue: ref("ADM"),
      foundry,
      codeNumberStatus: ref(null),
      codeNumber: ref(null),
      SNCodeList: ref([]),
      show: ref(false),
    };
  },
  methods: {
    // 生成SN码
    onCreateSNCode() {
      const productID = this.productValue; // 产品ID
      const supplierCode = this.supplierValue; // 供应链公司代码
      const foundryCode = this.foundryValue; //代工厂代码
      const reservePlace = "F"; //预留位
      const YTD = this.dateRule(); // 年月日
      const codeNumber = this.codeNumber;
      let isEmpty = false; // 非空验证
      if (codeNumber === 0 || codeNumber === "" || codeNumber === null) {
        this.codeNumberStatus = "error";
        isEmpty = true;
      }
      if (productID === "" || productID === null) {
        this.product.status.value = "error";
        console.log(this.product);
        isEmpty = true;
      }
      if (supplierCode === "" || supplierCode === null) {
        this.supplier.status.value = "error";
        isEmpty = true;
      }
      if (foundryCode === "" || foundryCode === null) {
        this.foundry.status.value = "error";
        isEmpty = true;
      }
      if (isEmpty) return;
      const number = existCodeNumber + codeNumber;

      let snArr = new Array();
      for (let i = existCodeNumber; i < number; i++) {
        if (i > 99999) {
          this.message.warning(`SN码流水号超出，当前流水号为：${i}`);
          break;
        }
        existCodeNumber = i + 1;
        let serialNumber = (i + 1).toString().padStart(5, "0"); //补0
        let sn = `${productID}/${supplierCode}${foundryCode}${reservePlace}${YTD}${serialNumber}`;
        snArr.push(sn);
      }
      this.show = true;
      let timeout = codeNumber * 0.025;
      setTimeout(
        () => {
          this.show = false;
          this.SNCodeList = [...this.SNCodeList, ...snArr];
        },
        timeout > 2499 ? 2499 : timeout
      );
    },

    // 清除Code
    onClearSNCode() {
      console.log("onClearSNCode");
      this.SNCodeList = [];
      existCodeNumber = 0;
    },

    // 导出表格
    onExportForm() {
      const SNCodeList = this.SNCodeList;
      if (SNCodeList.length <= 0) {
        this.message.warning("未生成SN码无法导出！");
        return;
      }
      let titleList = [
        {
          label: "序列",
          prop: "order_id",
          width: "4%",
        },
        {
          label: "SN码",
          prop: "sn_code",
          width: "40%",
        },
      ];
      let tableList = SNCodeList.map((code, index) => {
        return {
          sn_code: code,
        };
      });

      const product = this.product.options;
      // 产品ID对应地区名称
      const label = product.find((item) => item.value === this.productValue).label.match(/(\S*)：/)[1];
      let outfilename = `${label}${existCodeNumber}个SN码`; // 导出的文件名称
      let orderProp = "order_id"; // 序号列对应的字段名称
      exportExcel(titleList, tableList, outfilename, orderProp);
    },

    // SN码日期规则
    dateRule() {
      const date = new Date();
      const year = date.getFullYear().toString(); // 年 获取四位的年（yyyy）
      const month = date.getMonth(); // 月 获取月（0-11）
      const day = date.getDate() - 1; // 日 以数值返回天（1-31）
      const YY = year.charAt(year.length - 1);
      const MM = ["N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
      const DD = [
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "H",
        "J",
        "K",
        "M",
        "N",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ];
      return `${YY}${MM[month]}${DD[day]}`;
    },
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.form-panel {
  padding: 40px;
}
.card-wrap {
}

.column {
  display: flex;
  flex-direction: column;
}

.column-title {
  margin-bottom: 6px;
}

.operate {
  /* align-items: center; */
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
